package main

import (
	"strings"

	"github.com/extrame/goblet"
	"github.com/sirupsen/logrus"

	"gitee.com/bjf-fhe/apinx/config"
	"gitee.com/bjf-fhe/apinx/ctrl"
)

var cryptCfg config.Crypt
var apiCfg config.OpenAPI
var targetCfg config.Servers

func main() {

	s := goblet.Organize("apinx")
	s.AddConfig("crypt", &cryptCfg)
	s.AddConfig("openapi", &apiCfg)
	s.AddConfig("target", &targetCfg)

	if err := cryptCfg.Check(); err != nil {
		logrus.WithError(err).Fatal(`配置文件错误,请参考如下配置加密段，内容为加密密钥和加密向量:
		crypt:
			key: default_key_for_apinx
			tweak: 1D3E5A7C9B0D2F4H 
		`)
	}

	def, err := apiCfg.LoadDefinition()

	if err != nil {
		if strings.Contains(err.Error(), "The system cannot find the file specified") {
			//如果是空文件，那么就不报错，创建一个默认的OpenAPI定义，并且保存到文件中
			def, err = apiCfg.NewDefaultDefinition()
		}
	}

	if err == nil {
		err = targetCfg.CheckByDef(def)
	}

	if err != nil {
		logrus.WithError(err).Fatal("加载或创建OpenAPI定义失败")
	}

	s.ControlBy(&ctrl.Gateway{Def: def, Targets: targetCfg, ApiCfg: &apiCfg, Crypt: &cryptCfg})

	err = s.Run()
	if err != nil {
		logrus.WithError(err).Fatal("服务启动失败")
	}
}
